import React, { useState } from 'react';
import { Form, Input, Button, Tabs, message, Card, Typography, Row, Col } from 'antd';
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { loginUser, getVerificationCode, loginWithVerificationCode, clearError } from '../redux/features/userSlice';
import { validatePhone } from '../utils/tools';
import './LoginPage.css';

const { Title, Paragraph } = Typography;
const { TextArea } = Input;

const LoginPage = () => {
  const [activeTab, setActiveTab] = useState('password');
  const [passwordForm] = Form.useForm();
  const [codeForm] = Form.useForm();
  const [countdown, setCountdown] = useState(0);
  const dispatch = useDispatch();
  const { isLoading, error, isAuthenticated } = useSelector((state) => state.user);

  // 处理密码登录
  const handlePasswordLogin = async (values) => {
    try {
      await dispatch(loginUser(values)).unwrap();
      message.success('登录成功');
      // 登录成功后跳转到首页
      window.location.href = '/';
    } catch (error) {
      message.error(error?.message || '登录失败，请检查您的手机号码和密码');
    }
  };

  // 处理验证码登录
  const handleCodeLogin = async (values) => {
    try {
      await dispatch(loginWithVerificationCode(values)).unwrap();
      message.success('登录成功');
      // 登录成功后跳转到首页
      window.location.href = '/';
    } catch (error) {
      message.error(error?.message || '登录失败，请检查您的手机号码和验证码');
    }
  };

  // 处理获取验证码
  const handleGetCode = async () => {
    try {
      const phoneValue = codeForm.getFieldValue('phone');
      if (!phoneValue) {
        message.error('请先输入手机号码');
        return;
      }
      if (!validatePhone(phoneValue)) {
        message.error('请输入有效的手机号码');
        return;
      }

      await dispatch(getVerificationCode(phoneValue)).unwrap();
      message.success('验证码已发送，请注意查收');
      
      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prevCountdown) => {
          if (prevCountdown <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prevCountdown - 1;
        });
      }, 1000);
    } catch (error) {
      message.error(error?.message || '获取验证码失败，请稍后再试');
    }
  };

  // 清除错误信息
  React.useEffect(() => {
    if (error) {
      const timer = setTimeout(() => {
        dispatch(clearError());
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [error, dispatch]);

  // 如果已经登录，直接跳转到首页
  React.useEffect(() => {
    if (isAuthenticated) {
      window.location.href = '/';
    }
  }, [isAuthenticated]);

  // 验证手机号码
  const validatePhoneNumber = (rule, value) => {
    if (!value) {
      return Promise.reject('请输入手机号码');
    }
    if (!validatePhone(value)) {
      return Promise.reject('请输入有效的手机号码');
    }
    return Promise.resolve();
  };

  // 标签页配置项
  const tabItems = [
    {
      key: 'password',
      label: '密码登录',
      children: (
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordLogin}
          className="login-form"
        >
          <Form.Item
            label="手机号码"
            name="phone"
            rules={[
              { validator: validatePhoneNumber }
            ]}
          >
            <Input
              prefix={<MobileOutlined className="input-prefix" />}
              placeholder="请输入手机号码"
              maxLength={11}
            />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度应在6-20位之间' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="input-prefix" />}
              placeholder="请输入密码"
            />
          </Form.Item>

          <Form.Item className="login-button-group">
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={isLoading}
              className="login-button"
            >
              登录
            </Button>
          </Form.Item>
          
          <div style={{ textAlign: 'center', marginTop: 16 }}>
            还没有账号？ <a href="/register">立即注册</a>
          </div>
        </Form>
      ),
    },
    {
      key: 'code',
      label: '验证码登录',
      children: (
        <Form
          form={codeForm}
          layout="vertical"
          onFinish={handleCodeLogin}
          className="login-form"
        >
          <Form.Item
            label="手机号码"
            name="phone"
            rules={[
              { validator: validatePhoneNumber }
            ]}
          >
            <Input
              prefix={<MobileOutlined className="input-prefix" />}
              placeholder="请输入手机号码"
              maxLength={11}
            />
          </Form.Item>

          <Form.Item
            label="验证码"
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码应为6位数字' },
              { pattern: /^\d+$/, message: '验证码只能包含数字' }
            ]}
          >
            <Row gutter={12}>
              <Col xs={16}>
                <Input
                  prefix={<UserOutlined className="input-prefix" />}
                  placeholder="请输入验证码"
                  maxLength={6}
                />
              </Col>
              <Col xs={8}>
                <Button
                  type="link"
                  onClick={handleGetCode}
                  disabled={countdown > 0 || isLoading}
                  className="code-button"
                >
                  {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item className="login-button-group">
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={isLoading}
              className="login-button"
            >
              登录
            </Button>
          </Form.Item>
          
          <div style={{ textAlign: 'center', marginTop: 16 }}>
            还没有账号？ <a href="/register">立即注册</a>
          </div>
        </Form>
      ),
    },
  ];

  return (
    <div className="login-container">
      <Row justify="center" align="middle" className="login-row">
        <Col xs={24} sm={20} md={16} lg={12} xl={10} xxl={8}>
          <Card className="login-card">
            <div className="login-header">
              <Title level={2} className="login-title">设备二维码管理系统</Title>
              <Paragraph className="login-subtitle">请登录后继续操作</Paragraph>
            </div>
            
            <Tabs 
              activeKey={activeTab} 
              onChange={setActiveTab} 
              className="login-tabs"
              items={tabItems}
            />

            {error && (
              <div className="error-message">
                {typeof error === 'string' ? error : error.message || '发生错误，请稍后再试'}
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default LoginPage;